package net.lgpage.tool;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GsonTool {
	private static Gson gson;

	public static Gson getGson() {
		if(f == null){
			f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
		}
		if (gson == null) {
			GsonBuilder gb = new GsonBuilder();
			gb.registerTypeAdapter(java.sql.Date.class,
					new UtilDateSerializer()).setDateFormat(DateFormat.LONG);
			gb.registerTypeAdapter(java.sql.Date.class,
					new UtilDateDeserializer()).setDateFormat(DateFormat.LONG);
			gb.registerTypeAdapter(java.util.Date.class,
					new UtilDateSerializer()).setDateFormat(DateFormat.LONG);
			gb.registerTypeAdapter(java.util.Date.class,
					new UtilDateDeserializer()).setDateFormat(DateFormat.LONG);
			gson = gb.create();
		}
		return gson;
	}

	static SimpleDateFormat f;
	
	public static class UtilDateDeserializer implements JsonDeserializer<Date> {
		public Date deserialize(JsonElement json, Type typeOfT,
				JsonDeserializationContext context) throws JsonParseException {
			try {
				return f.parse(json.getAsJsonPrimitive().getAsString());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	public static class UtilDateSerializer implements JsonSerializer<Date> {
		public JsonElement serialize(Date src, Type typeOfSrc,
				JsonSerializationContext context) {
			return new JsonPrimitive(f.format(src));
		}
	}
	
	public static<T> List<T>getList(String jastr,Class<T>clazz){
		try {
			JSONArray ja = new JSONArray(jastr);
			List<T>list = new ArrayList<T>();
			for(int i =0;i<ja.length();i++){
				T t = GsonTool.getGson().fromJson(ja.getString(i), clazz);
				list.add(t);
			}
			return list;
		} catch (JSONException e) {
			System.out.println(e);
			return null;
		}
	}
	public static<T> List<T>getList(JSONArray ja,Class<T>clazz){
		try {
			List<T>list = new ArrayList<T>();
			for(int i =0;i<ja.length();i++){
				T t = GsonTool.getGson().fromJson(ja.getString(i), clazz);
				list.add(t);
			}
			return list;
		} catch (JSONException e) {
			System.out.println(e);
			return null;
		}
	}
}
